import { useCrudForm } from "@/composables/useCrudForm";
import { visitorFormConfig } from "../form-config";
import SysvisitorinformationApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysVisitorInformation,
  ISysVisitorInformationVm,
} from "../api/interface";

/**
 * 访客信息专用 Composable
 */
export function useVisitorInfo() {
  // 创建API实例
  const api = SysvisitorinformationApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
  };

  // 选项数据加载器
  const optionLoaders = {
    user: async () => {
      const commonApiInstance = commonApi();
      return await commonApiInstance.GetFrameworkUsers();
    },
  };

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysVisitorInformation, ISysVisitorInformationVm>(
    visitorFormConfig,
    apiConfig,
    optionLoaders
  );

  /**
   * 转换表单数据为API格式（新增）
   */
  const convertFormDataToApiFormatForCreate = (): ISysVisitorInformationVm => {
    return {
      Entity: {
        Name: crudForm.formData.name || null,
        Phone: crudForm.formData.phone || null,
        IdCardNo: crudForm.formData.idCardNo || null,
        IdCardFrontPhotoId: crudForm.formData.idCardFrontPhoto || null,
        IdCardBackPhotoId: crudForm.formData.idCardBackPhoto || null,
        Company: crudForm.formData.company || null,
        CarNo: crudForm.formData.carNo || null,
        UserId: crudForm.pickerValues.user || null,
        Remark: crudForm.formData.remark || null,
        BlackStatus: crudForm.pickerValues.blackStatus === "true" || false,
        BlackReason: crudForm.formData.blackReason || null,
      },
    };
  };

  /**
   * 转换表单数据为API格式（编辑）
   */
  const convertFormDataToApiFormatForEdit = (): ISysVisitorInformationVm => {
    const originalData = crudForm.originalData.value;
    if (!originalData) {
      throw new Error("原始数据不存在");
    }

    return {
      Entity: {
        ID: originalData.ID || null,
        Name: crudForm.formData.name || originalData.Name,
        Phone: crudForm.formData.phone || originalData.Phone,
        IdCardNo: crudForm.formData.idCardNo || originalData.IdCardNo,
        IdCardFrontPhotoId: crudForm.formData.idCardFrontPhoto || originalData.IdCardFrontPhotoId,
        IdCardBackPhotoId: crudForm.formData.idCardBackPhoto || originalData.IdCardBackPhotoId,
        Company: crudForm.formData.company || originalData.Company,
        CarNo: crudForm.formData.carNo || originalData.CarNo,
        UserId: crudForm.pickerValues.user || originalData.UserId,
        Remark: crudForm.formData.remark || originalData.Remark,
        BlackStatus: crudForm.pickerValues.blackStatus === "true" || originalData.BlackStatus || false,
        BlackReason: crudForm.formData.blackReason || originalData.BlackReason,
      },
    };
  };

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 访客基本信息
    name: "Name",
    phone: "Phone",
    idCardNo: "IdCardNo",
    company: "Company",
    carNo: "CarNo",
    user: "UserId", // 直接使用ID，让选择器处理逻辑来转换
    remark: "Remark",

    // 身份信息
    idCardFrontPhoto: "IdCardFrontPhotoId",
    idCardBackPhoto: "IdCardBackPhotoId",

    // 黑名单信息
    blackStatus: "BlackStatus",
    blackReason: "BlackReason",
  };

  /**
   * 加载访客详情数据
   */
  const loadVisitorDetail = async (id: string): Promise<boolean> => {
    const detail = await crudForm.getDetail(id);

    if (detail) {
      // 先使用通用转换
      crudForm.convertApiDataToFormData(detail, fieldMapping);

      // 添加特殊处理，确保选择器字段正确映射
      await ensurePickerFieldsMapping(detail);

      return true;
    }
    return false;
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理绑定用户
    if (apiData.UserId && visitorFormConfig.user?.optionsData) {
      const userOption = visitorFormConfig.user.optionsData.find(
        (item: any) => item.value === apiData.UserId
      );
      if (userOption) {
        crudForm.formData.user = userOption.text;
        crudForm.pickerValues.user = userOption.value;
      }
    }

    // 处理黑名单状态
    crudForm.formData.blackStatus = apiData.BlackStatus ? "黑名单" : "正常";
    crudForm.pickerValues.blackStatus = apiData.BlackStatus ? "true" : "false";
  };

  /**
   * 创建访客信息
   */
  const createVisitor = async (): Promise<{
    success: boolean;
    data?: ISysVisitorInformation;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForCreate();
    const result = await crudForm.create(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 保存访客信息（编辑）
   */
  const saveVisitor = async (): Promise<{
    success: boolean;
    data?: ISysVisitorInformation;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 验证关键数据
    if (!crudForm.originalData.value) {
      return {
        success: false,
        error: "原始数据丢失，请重新加载页面",
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForEdit();
    const result = await crudForm.update(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 访客信息专用方法
    loadVisitorDetail,
    createVisitor,
    saveVisitor,

    // API数据转换方法
    convertFormDataToApiFormatForCreate,
    convertFormDataToApiFormatForEdit,

    // 字段映射
    fieldMapping,
  };
}